package org.itzixi.service;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.itzixi.RedisKeyConstant;
import org.itzixi.mapper.ChatMessageMapper;
import org.itzixi.pojo.ChatMessage;
import org.itzixi.pojo.convertor.ChatMessageConvertor;
import org.itzixi.pojo.netty.ChatMsg;
import org.itzixi.utils.PagedGridResult;
import org.itzixi.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ChatMessageService {

    private final ChatMessageMapper chatMessageMapper;

    private final RedisOperator redisOperator;


    public void save(ChatMsg chatMsg){
        ChatMessage chatMessage = ChatMessageConvertor.INSTANCE.chatMsg2ChatMessage(chatMsg);
        chatMessageMapper.insert(chatMessage);

        String receiverId = chatMessage.getReceiverId();
        String senderId = chatMessage.getSenderId();
        // 通过redis进行累加未读消息
        String redisKey = String.join(StrUtil.COLON, RedisKeyConstant.CHAT_MSG_LIST, receiverId);
        redisOperator.incrementHash(redisKey, senderId, 1);
    }

    public PagedGridResult queryChatMsgList(String senderId, String receiverId, Integer page, Integer pageSize) {
        Page<ChatMessage> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.or(qw -> qw.lambda()
                        .eq(ChatMessage::getSenderId, senderId)
                        .eq(ChatMessage::getReceiverId, receiverId))
                .or(qw -> qw.lambda()
                        .eq(ChatMessage::getSenderId, receiverId)
                        .eq(ChatMessage::getReceiverId, senderId)).orderByDesc("chat_time");
        pageInfo = chatMessageMapper.selectPage(pageInfo, queryWrapper);
        List<ChatMessage> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        if (!CollectionUtils.isEmpty(records)){
            List<ChatMessage> sortedListByChatTime = records.stream()
                    .sorted(Comparator.comparing(ChatMessage::getChatTime))
                    .collect(Collectors.toList());
            return PagedGridResult.getPageInfo(page, pageSize, total, sortedListByChatTime);

        }



        return PagedGridResult.getPageInfo(page, pageSize, total, new ArrayList<>());

    }


    /**
     * 语音聊天的签收已读
     * @param msgId
     */
    public void updateMsgSignRead(String msgId) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setId(msgId);
        chatMessage.setIsRead(true);
        chatMessageMapper.updateById(chatMessage);
    }
}

